﻿Option Explicit On
Option Strict On

''' <summary>
''' Shared Hooks for Global Error Handling
''' </summary>
''' <remarks></remarks>
Public NotInheritable Class GlobalHandlers

#Region " Private Constructor "

    ''' <summary>
    ''' Private Constructor
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub New()
    End Sub

#End Region

#Region " Shared Methods "

    ''' <summary>
    ''' Hooks the error handling for the application
    ''' </summary>
    ''' <param name="ReportingEmailAddress">The Email address to send the error reports to</param>
    ''' <param name="SystemVersion">The Version of the application using the error management</param>
    ''' <param name="SystemName">The name of the application using the error management</param>
    ''' <remarks></remarks>
    Public Shared Sub HookErrorHandling(ByVal ReportingEmailAddress As String, ByVal SystemVersion As String, ByVal SystemName As String)

        ExceptionManager.ReportingEmailAddress = ReportingEmailAddress
        ExceptionManager.SystemName = SystemName
        ExceptionManager.SystemVersion = SystemVersion

        If (Not Debugger.IsAttached) Then
            AddHandler System.Windows.Forms.Application.ThreadException, AddressOf ThreadException
            AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException
        End If

    End Sub

    ''' <summary>
    ''' Unhooks the error handling for the application
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub UnhookErrorHandling()

        If (Not Debugger.IsAttached) Then
            RemoveHandler System.Windows.Forms.Application.ThreadException, AddressOf ThreadException
            RemoveHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException
        End If

    End Sub

    ''' <summary>
    ''' Handles WinForms Application Exceptions
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Shared Sub ThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
        HandleException(e.Exception)
    End Sub

    ''' <summary>
    ''' Handles any other UnHandled Exceptions
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Shared Sub UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
        HandleException(CType(e.ExceptionObject, Exception))
    End Sub

    ''' <summary>
    ''' Central error handler
    ''' </summary>
    ''' <param name="ex"></param>
    ''' <remarks></remarks>
    Private Shared Sub HandleException(ByVal ex As Exception)
        ExceptionManager.PublishException(ex, True)
    End Sub

#End Region

End Class
